<?php

/**
 * 小小宝（有好货）供应商SDK
 * @author hujian
 */

namespace App\Service\VendorClient\ShopxxbApi;

use App\Service\Code\Normal;
use App\Service\BaseService;
use Service\AppService\IdService;
use App\Service\TaskServer\TaskWorker;

class ShopXxbApiClient extends BaseService {
    private $config = [];

    public function __construct($apiBody = []) {
        $this->config = $apiBody;
    }

    /**
     * 创建订单
     * @param array $params
     * @return mixed
     */
    public function createOrder($param = []) {
        $orderInfo   = $param['supplierOrder'];
        $goodsList   = $param['orderGoods'];
        $order       = $param['order'];
        $binfo       = $param['binfo'];
        $companyInfo = $param['companyInfo'];
        $order_sn    = $orderInfo['supplier_dsn'];
        //支付流水号
        $pay_sn = $order['paySerial'] ?? $orderInfo['pay_sn'];
        //订单时间
        $order_time = $orderInfo['cd'] ? date('Y-m-d H:i:s', $orderInfo['cd']) : date('Y-m-d H:i:s', time());
        //支付时间
        $pay_time = isset($order['payTime']) && !empty($order['payTime']) ? date('Y-m-d H:i:s', $order['payTime']) : date('Y-m-d H:i:s', time());
        //运费分摊
        $deliver_money = $orderInfo['deliver_money'];
        //下单支付的时候支付信息
        $apply_extends = @json_decode($orderInfo['apply_extends'], true);
        //获取下单商品信息
        $palceOrderGoods = [];
        $totalGoodsMoney = '0.00';
        foreach ($goodsList as $key => $item) {
            //卖价
            $price = $item['price'];
            //商品购买规格数量
            $spec_num = $item['spec_num'];//1
            //商品购买数量
            $quantity = $item['quantity'];//2
            //实际购买数量(下单数量 X 起售数量)
            $buyAcount = $spec_num * $quantity;//2
            //商品税率
            $tax      = $item['tax_rate'];//0.0910
            $tax_rate = bcadd((string)$tax, '1.0000', 4);//1.0910
            //商品+税费
            $shipping_fee        = $key == 0 ? $deliver_money : 0;//10
            $single_shipping_fee = bcdiv((string)$shipping_fee, (string)$quantity, 3);//5
            //单个商品税费
            $single_shipping_fee = ceil((float)$single_shipping_fee * 100) / 100;//5
            //商品包邮单价
            $price = bcadd((string)$price, (string)$single_shipping_fee, 2);//56.80
            //包邮价格(总价)
            $goodsMoney = bcmul((string)$price, (string)$quantity, 2);
            //获取商品不含税价格 ,小数第三位收了之后再进行合计计算
            $goods_price = bcdiv((string)$goodsMoney, (string)$buyAcount, 3);
            //实际商品包邮单价
            $singleGoodsPrice = ceil((float)$goods_price * 100) / 100;
            //商品包邮单价
            // $price            = bcadd((string)$price, (string)$single_shipping_fee, 2);//56.80
            //包邮价格(总价)
            // $goodsMoney       = bcmul((string)$price, (string)$quantity, 2);//113.60
            //总商品金额
            $totalGoodsMoney = bcadd($totalGoodsMoney, $goodsMoney, 2);
            //下单商品组
            $goodsInfo = [
                'index'    => $key + 1,//顺序号
                'goodsNo'  => trim($item['supplier_skucode']),//小小宝商品SKU
                'quantity' => $buyAcount,//数量
                'price'    => $singleGoodsPrice,//商品价格（完税价），如果是含税价格，则订单信息里的税款（taxAmt）需传0
            ];
            ksort($goodsInfo);
            $palceOrderGoods[] = $goodsInfo;
        }
        $requestParam = [
            'sysCode'      => $this->config['sys_code'],//系统编号，对接时会分配 （目前是测试环境）
            // 'storeCode'    => $this->config['store_code'],//店铺编号，对应小小宝上创建的店铺编码
            'orderId'      => $order_sn,//订单号
            'preOrderNo'   => $order_sn,//原始订单号
            'payId'        => $order['paySerial'],//支付单号
            'province'     => $orderInfo['province'],//省
            'city'         => $orderInfo['city'],//市
            'region'       => $orderInfo['district'],//区
            'address'      => $orderInfo['receive_address'],//地址
            'identityNo'   => $orderInfo['buyer_idcard'],//身份证号
            'identityName' => $orderInfo['buyer_realname'],//身份证姓名
            'buyerRegNo'   => $orderInfo['buyer_phone'],//买家注册号，顾客在电商平台注册的账号 可以传购买人手机号
            'receiver'     => $orderInfo['receive_name'],//收货人
            'phoneNo'      => $orderInfo['recveive_phone'],//收货人联系电话
            'friAmt'       => '0.00',//运费（单位：元）,
            'disAmt'       => '0.00',//非现金抵扣金额（单位：元）
            'payAmt'       => $totalGoodsMoney,//商品货款（单位：元）
            'taxAmt'       => '0.00',//税款（单位：元）
            'totalAmt'     => $orderInfo['real_total_money'],//总支付金额（单位：元）
            'orderTime'    => $order_time,//订单时间，格式：yyyy-MM-dd  HH:mm:ss
            'payTime'      => $pay_time,//订单时间，格式：yyyy-MM-dd  HH:mm:ss
            'ebpCode'      => $order['enterpriseNum'] ?? $apply_extends['enterpriseNum'] ?? '',//电商平台海关10位编码
            'ebpName'      => $order['enterpriseName'] ?? $apply_extends['enterpriseName'] ?? '',//电商平台海关备案名称
            'payCode'      => $order['payCommanyCode'],//支付企业海关10位编码
            'payName'      => $order['payCommanyName'],//支付企业海关备案名称
            'itemList'     => $palceOrderGoods,
        ];
        if(isset($this->config['store_code']) && !empty($this->config['store_code'])){
            $requestParam['storeCode'] = $this->config['store_code'];
        }
        $data         = [
            'method' => 'createOrder',
            'data'   => $requestParam,
        ];
        $res          = $this->execute($data);
        if ($res['code'] == Normal::SUC) {
            return Normal::returnCode(Normal::SUC, "订单推送成功");
        }
        return $res;
    }

    /**
     * 取消订单
     * @param $data
     * @return array|string
     */
    public function cancelOrder($params = []) {
        $requestParam = [
            'preOrderNo' => $params['supplierOrder']['supplier_dsn'],
        ];
        $data         = [
            'method' => 'cancelOrder',
            'data'   => $requestParam,
        ];
        return $this->execute($data);
    }

    /**
     * 签名
     * @param $data
     * @return string
     */
    public function sign($data) {
        ksort($data);
        $arr = [];
        foreach ($data as $k => $v) {
            if (is_array($v)) {
                $v = $this->getStr($v);
            }
            $arr[] = "{$k}={$v}";
        }
        $str = "{" . implode(",", $arr) . "}";
        $str = $this->config['app_key'] . $str . $this->config['app_key'];
        return strtoupper(md5($str));
    }

    /**
     * 签名-设置商品
     * @param $data
     * @return string
     */
    public function getStr($v) {
        $sku_list = [];
        foreach ($v as $item) {
            $str = [];
            foreach ($item as $key => $v) {
                $str[] = "{$key}={$v}";
            }
            $str        = implode(",", $str);
            $sku_list[] = "{$str}";
        }
        return "[{" . (implode("},{", $sku_list)) . "}]";
    }

    /**
     * CURL请求
     * @param $params
     * @return mixed
     */
    public function execute($param = []) {
        $url    = $this->config['base_url'];
        $method = $param['method'];
        if (empty($url)) {
            return Normal::returnCode(Normal::FAIL, "接口地址不能为空");
        }
        if (empty($param['data'])) {
            return Normal::returnCode(Normal::FAIL, "数据不能为空");
        }
        if (empty($this->config[$method])) {
            return Normal::returnCode(Normal::FAIL, "当前仓库参数【{$method}】未配置");
        }
        $pushData  = [
            'userId'  => $this->config['user_id'],//小小宝用户ID
            'type'    => $this->config[$method],//请求接口类型
            'content' => $param['data'],//请求参数内容
            'sign'    => $this->sign($param['data']),//签名
        ];
        $parameter = [
            [
                'tag'    => 'shopxxb_' . $param['method'],
                'uid'    => IdService::instance()->getOtherID(),
                'url'    => $url,
                'data'   => $pushData,
                'method' => 'post',
                'format' => 'json',
                'header' => [
                    "Content-Type: application/json"
                ],
            ],
        ];
        $resTask   = TaskWorker::instance()->addTask($parameter);
        $resTask   = current($resTask);
        $response  = $resTask['response']['result'];
        $result    = @json_decode($response, true);
        if (isset($result['success']) && $result['success'] == true) {
            return Normal::returnCode(Normal::SUC, "操作成功", $result);
        } else {
            $msg = $response ? $response : '供应商接口请求失败';
            return Normal::returnCode(Normal::FAIL,$msg);
        }
    }
}